package com.jming.jike.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.jming.jike.entity.Employee;
import com.jming.jike.entity.User;
import com.jming.jike.util.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * mybatis 配置
 *
 * @author jinming.zhang
 */
@Slf4j
@Configuration
@MapperScan(basePackages = "com.jming.jike.mapper")
public class MybatisPlusConfig implements MetaObjectHandler {

    @Resource
    private HttpSession httpSession;

    @Resource
    private IdWorker idWorker;

    /**
     * 配置分页
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

    /**
     * 插入操作，自动填充
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("公共字段自动填充[insert]...");

        metaObject.setValue("createTime", new Date());
        metaObject.setValue("createUser", this.getOperId());
        metaObject.setValue("soleId", idWorker.nextId());
        metaObject.setValue("userId", this.getOperId());
    }

    /**
     * 更新操作，自动填充
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("公共字段自动填充[update]...");

        metaObject.setValue("updateUser", this.getOperId());
    }

    public Long getOperId() {

        // 如果为后台用户 则返回后台用户id
        if (httpSession.getAttribute("Employee") != null) {

            return ((Employee) httpSession.getAttribute("Employee")).getId();
            // 如果为前台用户 则返回前台用户id
        } else if (httpSession.getAttribute("User") != null) {

            return ((User) httpSession.getAttribute("User")).getId();
        }

        // 如果都未登录 则返回-1
        return 1L;
    }
}
